package com.poker.wiki.Service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.poker.common.utils.CopyUtil;
import com.poker.common.utils.SnowFlake;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import com.poker.wiki.Service.EbookService;
import com.poker.wiki.entity.Ebook;
import com.poker.wiki.entity.EbookExample;
import com.poker.wiki.mapper.EbookMapper;
import com.poker.wiki.req.EbookQueryReq;
import com.poker.wiki.req.EbookSaveReq;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookServiceImpl implements EbookService {

    @Resource
    EbookMapper ebookMapper;

    @Resource
    SnowFlake snowFlake;

    @Override
    public PageInfo<Ebook> getAllEbook(EbookQueryReq req) {

        EbookExample example = new EbookExample();
        EbookExample.Criteria criteria = example.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName())){
            criteria.andNameLike("%"+req.getName()+"%");
        }
        if (!ObjectUtils.isEmpty(req.getCategory2Id())){
            criteria.andCategory2IdEqualTo(req.getCategory2Id());
        }

        PageHelper.startPage(req.getPageNum(),req.getPageSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(example);
        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);

        return pageInfo;
    }

    @Override
    public void save(EbookSaveReq req) {

        Ebook ebook = CopyUtil.copy(req, Ebook.class);

        if (ObjectUtils.isEmpty(ebook.getId())){
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    @Override
    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
